package com.linchong.concurrency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-08 22:57
 * @Description:
 */
@Slf4j
public class SemaphoreExample4 {
	private final static int threadCount = 20;

	public static void main(String[] args) throws InterruptedException {

		ExecutorService exec = Executors.newCachedThreadPool();

		final Semaphore semaphore = new Semaphore(3);

		for (int i = 0; i < threadCount; i++) {
			final int threadNum = i;
			exec.execute(()->{
				try{
					//尝试获取许可，获取执行，否则丢弃
					if(semaphore.tryAcquire(5_000, TimeUnit.MILLISECONDS)){
						test(threadNum);
						semaphore.release();
					}
				}catch (Exception e){
					log.error("exception",e);
				}finally {
				}
			});
		}
		exec.shutdown();
	}

	private static void test(int threadNum) throws InterruptedException {
		log.info("{}",threadNum);
		Thread.sleep(1_000);


	}
}
